package com.ycy;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.redisson.api.RLock;

/**
 * cache aside
 */
public class CacheDemo {

  GsonBuilder gsonBuilder = new GsonBuilder();

  Gson gson = gsonBuilder.create();

  public Product get(Integer productId) {

    Product product = getProductFromCache(productId);
    if (product != null) {
      return product;
    }

    //热点key 并发重建时，mysql请求增多，所以加锁只保证一个线程请求mysql
    RLock lock = RedisCURD.getLock(String.valueOf(productId));

    lock.lock();
    //双重检查机制
    product = getProductFromCache(productId);
    if (product != null) {
      return product;
    }
    try {
      //从数据库加载
      Product productDao = getProductFromDao(productId);
      RedisCURD.set(String.valueOf(productId), gson.toJson(productDao), 10);
      return productDao;
    } finally {
      lock.unlock();
    }
  }

  private Product getProductFromDao(Integer productId) {
    //从数据库中获取
    return new Product();
  }

  public Product getProductFromCache(Integer productId) {
    String s = RedisCURD.get(String.valueOf(productId), 10);
    if (s == null) return null;
    GsonBuilder gsonBuilder = new GsonBuilder();
    Gson gson = gsonBuilder.create();
    Product product = gson.fromJson(s, Product.class);
    return product;
  }


  public void update(Product product) {

  }

  public void insert(Product product) {

  }

  class Product {

    public Integer productId;

    public String productName;

    public Integer getProductId() {
      return productId;
    }

    public void setProductId(Integer productId) {
      this.productId = productId;
    }

    public String getProductName() {
      return productName;
    }

    public void setProductName(String productName) {
      this.productName = productName;
    }
  }


}
